package com.qinke.mqcluster.utils;

import java.io.*;
import java.util.Properties;

public class ConfigUtil {
    private static String configFileName = "config.properties";
    //获取配置文件中的内容，配置文件三个位置
    //1.优先jar同级文件夹config中的config.properties
    //2.次优先jar同级的config.properties
    //3.最后取代码中根目录的配置文件
    public static String getConfig(String key) {
        InputStream inputStream = getConfigPath();
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            return String.valueOf(properties.get(key));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static InputStream getConfigPath() {
        try {
            String path = System.getProperty("user.dir");
            String path1 = path + "/config/" + configFileName;
            File file1 = new File(path1);
            if (file1.exists()) {
                return new FileInputStream(file1);
            } else {
                String path2 = path += "/" + configFileName;
                File file2 = new File(path2);
                if (file2.exists()) {
                    return new FileInputStream(file2);
                } else {
                    InputStream inputStream = ConfigUtil.class.getResourceAsStream("/"+configFileName);
                    if(null==inputStream){
                        throw new RuntimeException("没有发现配置文件，请检查配置文件是否存在");
                    }else{
                        return  inputStream;
                    }

                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("没有发现配置文件，请检查配置文件是否存在");
        }
    }
}
